import React, { useEffect, useState } from 'react';
import type { ProvinceData } from '../App';

interface MetricsData {
  metrics: {
    cpuUsage: number;
    memoryUsage: number;
    networkTraffic: number;
    storage: number;
  };
  subMetrics: {
    processingPower: string;
    computeNodes: number;
  };
}

interface TextLabels {
  cpuUsageLabel: string;
  memoryUsageLabel: string;
  networkTrafficLabel: string;
  storageLabel: string;
  processingPowerLabel: string;
  computeNodesLabel: string;
}

interface MetricsPanelProps {
  textLabels?: TextLabels;
  selectedProvince?: {
    name: string;
    data: ProvinceData | null;
  } | null;
}

export const MetricsPanel: React.FC<MetricsPanelProps> = ({ textLabels, selectedProvince }) => {
  const [metricsData, setMetricsData] = useState<MetricsData | null>(null);
  const [loading, setLoading] = useState<boolean>(true);
  const [error, setError] = useState<string | null>(null);

  // 默认标签文本
  const defaultLabels: TextLabels = {
    cpuUsageLabel: "CPU使用率",
    memoryUsageLabel: "内存使用",
    networkTrafficLabel: "网络流量",
    storageLabel: "存储",
    processingPowerLabel: "处理能力",
    computeNodesLabel: "计算节点"
  };

  // 合并默认标签和传入的标签
  const labels = textLabels ? { ...defaultLabels, ...textLabels } : defaultLabels;

  // 从JSON文件加载指标数据
  useEffect(() => {
    const fetchMetricsData = async () => {
      try {
        const response = await fetch('/data/charts/metrics-data.json');
        if (!response.ok) {
          throw new Error(`HTTP error! Status: ${response.status}`);
        }
        const data = await response.json();
        setMetricsData(data);
        setLoading(false);
      } catch (err) {
        console.error('加载指标数据失败:', err);
        setError('加载指标数据失败，请检查网络连接');
        setLoading(false);
      }
    };

    fetchMetricsData();
    
    // 设置定期刷新数据的间隔（每60秒刷新一次）
    const intervalId = setInterval(fetchMetricsData, 60000);
    
    return () => {
      clearInterval(intervalId);
    };
  }, []);

  // 根据是否有选中的省份来确定显示的数据
  const getProvinceData = () => {
    if (selectedProvince && selectedProvince.data) {
      // 如果有选中省份且有数据，返回省份数据
      return {
        metrics: {
          cpuUsage: selectedProvince.data.cpuUsage,
          memoryUsage: selectedProvince.data.memoryUsage,
          networkTraffic: selectedProvince.data.networkTraffic,
          storage: selectedProvince.data.storage
        },
        subMetrics: {
          processingPower: selectedProvince.data.processingPower,
          computeNodes: selectedProvince.data.computeNodes
        }
      };
    } else {
      // 如果没有任何数据，返回默认值
      return {
        metrics: {
          cpuUsage: 0,
          memoryUsage: 0,
          networkTraffic: 0,
          storage: 0
        },
        subMetrics: {
          processingPower: "0 TFLOPS",
          computeNodes: 0
        }
      };
    }
  };

  if (loading) {
    return (
      <div className="metrics-panel loading-container">
        <div className="loading">加载中...</div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="metrics-panel error-container">
        <div className="error">{error}</div>
      </div>
    );
  }

  if (!metricsData) {
    return (
      <div className="metrics-panel error-container">
        <div className="error">无法加载数据</div>
      </div>
    );
  }

  // 获取省份数据
  const provinceData = getProvinceData();

  return (
    <div className="metrics-panel">
      <h2>系统指标</h2>
      
      {/* 全国指标 */}
      <div className="metrics-section">
        <h3 className="section-title">全国</h3>
        <div className="metric-item">{labels.cpuUsageLabel}: {metricsData.metrics.cpuUsage}%</div>
        <div className="metric-item">{labels.memoryUsageLabel}: {metricsData.metrics.memoryUsage} MB</div>
        <div className="metric-item">{labels.networkTrafficLabel}: {metricsData.metrics.networkTraffic} KB/s</div>
        <div className="metric-item">{labels.storageLabel}: {metricsData.metrics.storage} GB</div>
        <div className="sub-metrics">
          <span>{labels.processingPowerLabel}: {metricsData.subMetrics.processingPower}</span>
          <span>{labels.computeNodesLabel}: {metricsData.subMetrics.computeNodes}</span>
        </div>
      </div>
      
      {/* 省份指标 - 仅在选中省份时显示 */}
      {selectedProvince && selectedProvince.data && (
        <div className="metrics-section province-metrics">
          <h3 className="section-title">{selectedProvince.name}</h3>
          <div className="metric-item">{labels.cpuUsageLabel}: {provinceData.metrics.cpuUsage}%</div>
          <div className="metric-item">{labels.memoryUsageLabel}: {provinceData.metrics.memoryUsage} GB</div>
          <div className="metric-item">{labels.networkTrafficLabel}: {provinceData.metrics.networkTraffic} MB/s</div>
          <div className="metric-item">{labels.storageLabel}: {provinceData.metrics.storage} TB</div>
          <div className="sub-metrics">
            <span>{labels.processingPowerLabel}: {provinceData.subMetrics.processingPower}</span>
            <span>{labels.computeNodesLabel}: {provinceData.subMetrics.computeNodes}</span>
          </div>
        </div>
      )}
    </div>
  );
}; 